'''
Created on Jun 13, 2012

@author: thomas_dao
'''

from google.appengine.ext import ndb
from entity.entity import Rating

@ndb.tasklet
def count_by_event(event_key, **q_options):
    qry = Rating.query(Rating.event == event_key)
    count = yield qry.count_async(**q_options)
    raise ndb.Return(count)

@ndb.tasklet
def count_by_event_list(event_key_list, **q_options):
    counts = []
    for event_key in event_key_list:
        count = yield count_by_event(event_key, **q_options)
        counts.append(count)
                
    raise ndb.Return(counts)

@ndb.tasklet
def rating_by_event(event_key, **q_options):
    qry = Rating.query(Rating.event == event_key)
    rating_list = yield qry.fetch_async(**q_options)
    
    total_rating = 0
    avg_rating = 0
    
    for rating in rating_list:
        total_rating = total_rating + rating.rating
        
    if rating_list and len(rating_list) >0:
        avg_rating = total_rating/len(rating_list)
    raise ndb.Return(avg_rating)

@ndb.tasklet
def rating_by_event_list(event_key_list, **q_options):
    avg_ratings = []
    for event_key in event_key_list:
        avg_rating = yield rating_by_event(event_key, **q_options)
        avg_ratings.append(avg_rating)
                
    raise ndb.Return(avg_ratings)